import UIKit
import SwiftEventBus

class FavoriteCreatorViewController: CompletionViewController{
    var emptyView: UIView = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        showDeleteButton = true
        addEmptyView()
        let createRoleButton = UIButton(type: .custom)
        createRoleButton.setTitle("添加收藏", for: .normal)
        createRoleButton.layer.cornerRadius = 21
        createRoleButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        createRoleButton.frame.size = CGSize(width: 68, height: 20)
        createRoleButton.backgroundColor = .primaryColor
        createRoleButton.addTarget(self, action: #selector(createFavorite(_:)), for: .touchUpInside)
        self.view.addSubview(createRoleButton)
        createRoleButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.bottomLayoutGuide.snp.top).offset(-12)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width*2/3)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.view).offset(32)
            make.bottom.equalTo(self.view).offset(-60)
            make.width.equalTo(self.view)
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_DELETE_COMPLETION) { result in
            if let result = result{
                
                let alertController = UIAlertController(title: "提示",
                                                        message: "确定要删除此收藏吗？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "删除", style: .default, handler: {
                    action in
                    let deleteRole : Completion = result.object as! Completion
                    var index = 0
                    for role in self.list{
                        if role.title == deleteRole.title && role.subTitle == deleteRole.subTitle{
                            break
                        }
                        index = index + 1
                    }
                    self.list.remove(at: index)
                    self.tableView.reloadData()
                    self.updateLocalJson()
                    self.emptyView.isHidden = false
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
                
            }
            
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_ADD_COMPLETION) { result in
            if let result = result{
                let addCompletion : Completion = result.object as! Completion
                if self.isExist(addCompletion){
                    self.view.makeToast("已收藏",position: .center)
                }else{
                    
                    self.list.append(addCompletion)
                    self.tableView.reloadData()
                    
                    self.updateLocalJson()
                    
                    self.emptyView.isHidden = true
                }
            }
            
        }
        
        getLocalJson()
    }
    func isExist(_ completion: Completion) -> Bool{
        var  exist = false
        for item in list{
            if item.title == completion.title{
                exist = true
                break
            }
        }
        
        return exist
    }
    
    func getLocalJson(){
        if let json = StoreManager.getFavoriteCreatorJson(), !json.contains("[]"){
            self.parseJson(json: json)
        }else{
            emptyView.isHidden = false
        }
        
    }
    
    func parseJson(json: String?){
        
        if let string = json{
            let data = Data(string.utf8)
            do {
                let jsonDecoder = JSONDecoder()
                let completionResponse = try jsonDecoder.decode(CompletionResponse.self, from: data)
                if !completionResponse.data.isEmpty{
                    StoreManager.setFavoriteCreatorJson(json: string)
                    list = completionResponse.data
                    self.tableView.reloadData()
                }
                
                
            } catch {
                
                print(error)
            }
        }
        
    }
    
    func updateLocalJson(){
        do {
            var completionResponse = CompletionResponse(code: 200, data: self.list, message: "success")
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(completionResponse)
            let json = String(data: jsonData, encoding: String.Encoding.utf8)
            if let jsonString = json{
                StoreManager.setFavoriteCreatorJson(json: jsonString)
            }
        } catch {
            print(error)
        }
    }
    
    @objc private func createFavorite(_ sender: Any) {
        
        let detailViewController = CompletionTabViewController()
        detailViewController.pageTitle = "点击添加"
        detailViewController.isFavorite = true
        detailViewController.myNavigationController = myNavigationController
        myNavigationController?.pushViewController(detailViewController, animated: true)
        
        print("handleRightBarButtonTapped")
    }
    
    func addEmptyView(){
       
            emptyView.backgroundColor = .white
            let emptyLabel = UILabel()
            emptyLabel.text = "暂无收藏"
            emptyLabel.textColor = .gray
            emptyLabel.font = UIFont.systemFont(ofSize: 16,weight: .regular)
            emptyView.addSubview(emptyLabel)
            self.view.insertSubview(emptyView, at: 0)
            emptyLabel.snp.makeConstraints { make in
                make.center.equalTo(emptyView)
            }
            emptyView.snp.makeConstraints { make in
                make.edges.equalTo(self.view)
            }
        emptyView.isHidden = true
        
    }
    
}
